package com.milk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.milk.context.BaseContext;
import com.milk.dto.CommonPageQueryDTO;
import com.milk.entity.Coupon;
import com.milk.entity.User;
import com.milk.entity.UserCoupon;
import com.milk.exception.BaseException;
import com.milk.mapper.CouponMapper;
import com.milk.mapper.UserCouponMapper;
import com.milk.mapper.UserMapper;
import com.milk.result.PageResult;
import com.milk.service.ICouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milk.vo.UserCouponVo;
import com.milk.vo.UserLotteryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 优惠券 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-27
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 查询所有优惠卷
     * @return
     */
    public List<UserCouponVo> selectAll() {

        List<UserCouponVo> list = new ArrayList<>();
        QueryWrapper<UserCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", BaseContext.getCurrentId());
        List<UserCoupon> userCoupons = userCouponMapper.selectList(queryWrapper);
        for (UserCoupon userCoupon : userCoupons) {
            UserCouponVo userCouponVo = new UserCouponVo();
            BeanUtils.copyProperties(userCoupon,userCouponVo);

            Coupon coupon = couponMapper.selectById(userCoupon.getCouponId());

            userCouponVo.setName(coupon.getName());
            userCouponVo.setImage(coupon.getImage());

            list.add(userCouponVo);
        }
        return list;
    }

    /**
     * 查询可以积分兑换的优惠卷
     * @return
     */
    public List<Coupon> selectIntegral() {
//        QueryWrapper<Coupon> qw = new QueryWrapper<>();
//        qw.ne("integral",null);
//        qw.eq("integral",40);
        return couponMapper.selectListCanIntegral();
    }

    /**
     * 积分兑换
     * @param coupon
     */
    @Transactional
    public void exchange(Coupon coupon) {
        coupon = couponMapper.selectById(coupon.getId());
        Long userId = BaseContext.getCurrentId();
        //减少积分
        User user = userMapper.selectById(userId);
        System.out.println(coupon.getIntegral());
        System.out.println(user.getIntegral());
        if (user.getIntegral()-coupon.getIntegral()<0){
            throw new BaseException("积分不足");
        }
        user.setIntegral(user.getIntegral()-coupon.getIntegral());
        userMapper.updateById(user);

        //减少库存
        if (coupon.getTotalQuantity()-1<0){
            throw new BaseException("优惠卷不足");
        }
        coupon.setTotalQuantity(coupon.getTotalQuantity()-1);
        couponMapper.updateById(coupon);

        //添加到用户优惠卷中
        QueryWrapper<UserCoupon> qw = new QueryWrapper<>();
        qw.eq("user_id",userId);
        qw.eq("coupon_id",coupon.getId());
        UserCoupon userCoupon1 = userCouponMapper.selectOne(qw);
        if ( userCoupon1== null){
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setCouponId(coupon.getId());
            userCoupon.setUserId(userId);
            userCoupon.setNumber(1);
            userCoupon.setValidFrom(coupon.getCreatedAt());
            userCoupon.setValidUntil(coupon.getCreatedAt().plusDays(coupon.getValidTime()));
            userCouponMapper.insert(userCoupon);
        }else {
            userCoupon1.setNumber(userCoupon1.getNumber()+1);
            userCouponMapper.updateById(userCoupon1);
        }
    }

    /**
     * sdk兑换
     * @param sdk
     */
    public String  exchangeSdk(String sdk) {
        QueryWrapper<Coupon> qw = new QueryWrapper<>();
        qw.eq("sdk",sdk);
        Coupon coupon = couponMapper.selectOne(qw);
        if (coupon == null){
            return "此SDK码无效";
        }else {
            QueryWrapper<UserCoupon> qw1 = new QueryWrapper<>();
            qw1.eq("user_id",BaseContext.getCurrentId());
            qw1.eq("coupon_id",coupon.getId());
            List<UserCoupon> userCoupons = userCouponMapper.selectList(qw1);
            if (userCoupons!=null){
                UserCoupon userCoupon = userCoupons.get(0);
                userCoupon.setNumber(userCoupon.getNumber()+1);
                userCouponMapper.updateById(userCoupons);
            }else {
                UserCoupon userCoupon = new UserCoupon();
                userCoupon.setCouponId(coupon.getId());
                userCoupon.setUserId(BaseContext.getCurrentId());
                userCoupon.setNumber(1);
                userCoupon.setValidFrom(coupon.getCreatedAt());
                userCoupon.setValidUntil(coupon.getCreatedAt().plusDays(coupon.getValidTime()));
                userCouponMapper.insert(userCoupon);
            }
            return "兑换成功";
        }
    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    public PageResult selectPageQuery(CommonPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<Coupon> page = couponMapper.pageQuery(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 查找能积分兑换的优惠卷
     * @param dto
     * @return
     */
    public PageResult selectByIntegral(CommonPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<Coupon> page = couponMapper.pageQueryByIntegral(dto);
        return new PageResult(page.getTotal(),page.getResult());

    }

    /**
     * 取消这个优惠卷的积分兑换
     * @param id
     */
    public void deleteIntegral(Long id) {
        couponMapper.updateIntegralById(id);
    }

    /**
     * 查找能SDK兑换的优惠卷
     * @param dto
     * @return
     */
    public PageResult selectBySDK(CommonPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<Coupon> page = couponMapper.pageQueryBySDK(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 取消这个优惠卷的SDK兑换
     * @param id
     */
    public void deleteSDK(Long id) {
        couponMapper.updateSDKById(id);
    }

    /**
     * 查看没有积分兑换的优惠卷
     * @param dto
     * @return
     */
    public PageResult selectByNoIntegral(CommonPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<Coupon> page = couponMapper.pageQueryByNoIntegral(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 查看没有SDK兑换的优惠卷
     * @param dto
     * @return
     */
    public PageResult selectByNoSDK(CommonPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<Coupon> page = couponMapper.pageQueryByNoSDK(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }


}
